import express from 'express';
import { authenticateToken } from '../middleware/auth.js';
import pool from '../config/db.js';

const router = express.Router();

// 创建订单
router.post('/', authenticateToken, async (req, res) => {
  const connection = await pool.getConnection();
  
  try {
    await connection.beginTransaction();
    
    const { 
      items, 
      shipping_address_id, 
      payment_method, 
      gift_message = null,
      promo_code = null,
      discount = 0,
      shipping_fee = 0
    } = req.body;
    
    console.log('Creating order with data:', req.body);
    
    if (!items || !Array.isArray(items) || items.length === 0) {
      return res.status(400).json({
        success: false,
        message: '订单商品不能为空'
      });
    }
    
    if (!shipping_address_id) {
      return res.status(400).json({
        success: false,
        message: '收货地址不能为空'
      });
    }
    
    if (!payment_method) {
      return res.status(400).json({
        success: false,
        message: '支付方式不能为空'
      });
    }
    
    // 生成订单号 - 不使用 uuid，使用时间戳和随机数
    const orderNumber = `ORD${Date.now()}${Math.floor(Math.random() * 1000)}`;
    
    // 计算订单总金额
    let totalAmount = 0;
    
    // 获取商品信息
    const productIds = items.map(item => item.product_id);
    const [products] = await connection.query(
      'SELECT id, price, stock FROM products WHERE id IN (?)',
      [productIds]
    );
    
    // 创建商品ID到价格的映射
    const productMap = {};
    products.forEach(product => {
      productMap[product.id] = {
        price: product.price,
        stock: product.stock
      };
    });
    
    // 验证库存并计算总金额
    for (const item of items) {
      const product = productMap[item.product_id];
      
      if (!product) {
        await connection.rollback();
        return res.status(400).json({
          success: false,
          message: `商品ID ${item.product_id} 不存在`
        });
      }
      
      if (product.stock < item.quantity) {
        await connection.rollback();
        return res.status(400).json({
          success: false,
          message: `商品库存不足`
        });
      }
      
      totalAmount += product.price * item.quantity;
    }
    
    // 应用折扣
    totalAmount = Math.max(0, totalAmount - discount);
    
    // 添加运费
    totalAmount += shipping_fee;
    
    // 创建订单
    const [orderResult] = await connection.query(
      `INSERT INTO orders (
        order_no, 
        user_id, 
        shipping_address_id, 
        total_amount, 
        status, 
        payment_method, 
        payment_status,
        gift_message,
        promo_code,
        discount,
        shipping_fee
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        orderNumber,
        req.user.id,
        shipping_address_id,
        totalAmount,
        'pending',
        payment_method,
        'unpaid',
        gift_message,
        promo_code,
        discount,
        shipping_fee
      ]
    );
    
    const orderId = orderResult.insertId;
    
    // 创建订单商品
    for (const item of items) {
      const product = productMap[item.product_id];
      
      await connection.query(
        `INSERT INTO order_items (
          order_id, 
          product_id, 
          quantity, 
          price,
          attributes
        ) VALUES (?, ?, ?, ?, ?)`,
        [
          orderId,
          item.product_id,
          item.quantity,
          product.price,
          item.attributes ? JSON.stringify(item.attributes) : null
        ]
      );
      
      // 更新商品库存和销量
      await connection.query(
        'UPDATE products SET stock = stock - ?, sales = sales + ? WHERE id = ?',
        [item.quantity, item.quantity, item.product_id]
      );
    }
    
    await connection.commit();
    
    res.status(201).json({
      success: true,
      message: '订单创建成功',
      order: {
        id: orderId,
        order_no: orderNumber,
        total_amount: totalAmount
      }
    });
  } catch (error) {
    await connection.rollback();
    console.error('Error creating order:', error);
    res.status(500).json({
      success: false,
      message: '创建订单失败'
    });
  } finally {
    connection.release();
  }
});

// 获取订单列表
router.get('/', authenticateToken, async (req, res) => {
  try {
    const [orders] = await pool.query(
      `SELECT 
        o.*, 
        a.recipient_name, 
        a.phone, 
        a.province, 
        a.city, 
        a.district, 
        a.detail_address
      FROM orders o
      LEFT JOIN addresses a ON o.shipping_address_id = a.id
      WHERE o.user_id = ?
      ORDER BY o.created_at DESC`,
      [req.user.id]
    );
    
    // 获取订单商品
    for (let order of orders) {
      const [items] = await pool.query(
        `SELECT 
          oi.*, 
          p.name, 
          p.image
        FROM order_items oi
        JOIN products p ON oi.product_id = p.id
        WHERE oi.order_id = ?`,
        [order.id]
      );
      
      // 处理图片路径
      items.forEach(item => {
        if (item.image && !item.image.startsWith('http')) {
          item.image = `${req.protocol}://${req.get('host')}/uploads/${item.image}`;
        }
      });
      
      order.items = items;
    }
    
    res.json(orders);
  } catch (error) {
    console.error('Error fetching orders:', error);
    res.status(500).json({
      success: false,
      message: '获取订单失败'
    });
  }
});

// 获取订单详情
router.get('/:id', authenticateToken, async (req, res) => {
  try {
    const [orders] = await pool.query(
      `SELECT 
        o.*, 
        a.recipient_name, 
        a.phone, 
        a.province, 
        a.city, 
        a.district, 
        a.detail_address
      FROM orders o
      LEFT JOIN addresses a ON o.shipping_address_id = a.id
      WHERE o.id = ? AND o.user_id = ?`,
      [req.params.id, req.user.id]
    );
    
    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    const order = orders[0];
    
    // 获取订单商品
    const [items] = await pool.query(
      `SELECT 
        oi.*, 
        p.name, 
        p.image
      FROM order_items oi
      JOIN products p ON oi.product_id = p.id
      WHERE oi.order_id = ?`,
      [order.id]
    );
    
    // 处理图片路径
    items.forEach(item => {
      if (item.image && !item.image.startsWith('http')) {
        item.image = `${req.protocol}://${req.get('host')}/uploads/${item.image}`;
      }
    });
    
    order.items = items;
    
    res.json(order);
  } catch (error) {
    console.error('Error fetching order:', error);
    res.status(500).json({
      success: false,
      message: '获取订单详情失败'
    });
  }
});

// 取消订单
router.post('/:id/cancel', authenticateToken, async (req, res) => {
  const connection = await pool.getConnection();
  
  try {
    await connection.beginTransaction();
    
    // 查询订单
    const [orders] = await connection.query(
      'SELECT * FROM orders WHERE id = ? AND user_id = ?',
      [req.params.id, req.user.id]
    );
    
    if (orders.length === 0) {
      await connection.rollback();
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    const order = orders[0];
    
    // 只有待付款的订单可以取消
    if (order.status !== 'pending' && order.payment_status !== 'unpaid') {
      await connection.rollback();
      return res.status(400).json({
        success: false,
        message: '只有待付款的订单可以取消'
      });
    }
    
    // 更新订单状态
    await connection.query(
      'UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?',
      ['cancelled', order.id]
    );
    
    // 恢复商品库存
    const [items] = await connection.query(
      'SELECT product_id, quantity FROM order_items WHERE order_id = ?',
      [order.id]
    );
    
    for (const item of items) {
      await connection.query(
        'UPDATE products SET stock = stock + ?, sales = sales - ? WHERE id = ?',
        [item.quantity, item.quantity, item.product_id]
      );
    }
    
    await connection.commit();
    
    res.json({
      success: true,
      message: '订单已取消'
    });
  } catch (error) {
    await connection.rollback();
    console.error('Error cancelling order:', error);
    res.status(500).json({
      success: false,
      message: '取消订单失败'
    });
  } finally {
    connection.release();
  }
});

// 更新订单状态
router.put('/:id/status', authenticateToken, async (req, res) => {
  try {
    const orderId = req.params.id;
    const { status, payment_status } = req.body;
    
    if (!status) {
      return res.status(400).json({
        success: false,
        message: '状态不能为空'
      });
    }
    
    // 验证订单属于当前用户
    const [orderRows] = await pool.query(
      'SELECT * FROM orders WHERE id = ? AND user_id = ?',
      [orderId, req.user.id]
    );
    
    if (orderRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    // 更新订单状态
    if (payment_status) {
      // 如果提供了支付状态，同时更新支付状态
      await pool.query(
        'UPDATE orders SET status = ?, payment_status = ?, updated_at = NOW() WHERE id = ?',
        [status, payment_status, orderId]
      );
    } else {
      // 否则只更新订单状态
      await pool.query(
        'UPDATE orders SET status = ?, updated_at = NOW() WHERE id = ?',
        [status, orderId]
      );
    }
    
    res.json({
      success: true,
      message: '订单状态已更新'
    });
  } catch (error) {
    console.error('Error updating order status:', error);
    res.status(500).json({
      success: false,
      message: '更新订单状态失败'
    });
  }
});

// 通过订单号查询订单
router.get('/by-number/:orderNo', authenticateToken, async (req, res) => {
  try {
    const { orderNo } = req.params;
    
    // 查询订单
    const [orders] = await pool.query(
      'SELECT * FROM orders WHERE order_no = ? AND user_id = ?',
      [orderNo, req.user.id]
    );
    
    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    return res.json({
      success: true,
      order: orders[0]
    });
  } catch (error) {
    console.error('Error fetching order by number:', error);
    res.status(500).json({
      success: false,
      message: '获取订单失败'
    });
  }
});

export default router; 